#!/usr/bin/env python
#coding:utf8

import admin
import datetime 
import man
import time
import json
import pickle
from prettytable import PrettyTable

def read_user_data():
    with open('bank.pkl') as f:
        user_dict = pickle.load(f)
        return user_dict

def write_data(user_dict):
    with open('bank.pkl','wb') as f:
        pickle.dump(user_dict, f)

def user_status(user,user_dict):
    if user_dict[user]['status'] == 'ok':
        return True
    else:
        return False

def user_lock(user,user_dict,file_name='bank.pkl'):
    user_dict[user]['status'] = 'lock'
    write_data(user_dict)
    #print user_dict
    print '%s 用户已锁定，请联系管理员。' % user
    
def user_auth(user,passwd,user_dict):
    if user_dict[user]['passwd'] == passwd:
        return True
    else:
        return False

def user_credits(user,user_dict):
    return user_dict[user]['money']

def user_login_bank(user):
    user_dict = read_user_data()
    #print user_dict
    login = True
    count = 0
    while login:
        if user in user_dict: #判断用户输入名称是否正确
            count += 1
            #print 'count --->',count
            if count > 3: #判断重试次数是否超过三次
                user_lock(user,user_dict)
                login = False
            elif user_status(user,user_dict):#判断状态是否为OK状态
                user_passwd = raw_input('\033[33m请输入密码： \033[0m').strip()
                if user == 'admin':
                    if user_auth(user,user_passwd,user_dict):
                        admin.admin()
                elif user_auth(user,user_passwd,user_dict):
                    print '\033[32m中国银行欢迎您\n \033[0m'
                    return True
                else:
                    print '\033[31m您输入的密码错误\033[0m'
                    continue
            else:
                print '\033[31m该用户已经锁定，尽快联系管理员\033[0m'
                return False
            
        else:
            login = False
            return False
            print('\033[33m您输入的用户名不存在\033[0m')
        
def bank_interface():
    status = True
    while status:
        username = raw_input('\033[33m请输入用户名 (Q\q退出)：\033[0m').strip()
        user_dict = read_user_data()
        if username == 'q' or username == 'Q':
            man.man1()            
        #print '4444444444444444444444444444444444444',user_dict
        if user_login_bank(username):
            while True:
                list1 = ['列出账单','列出用户状态', '转账', '现金还款','取现','退出']
                for index,v in enumerate(list1):
                    print '\033[32m%s : %s\033[0m' % (index,v)
                user_input = raw_input('\033[33m请输入 ID :\033[0m').strip()
                if user_input == '0': #列出用户账单
                    user_dict = read_user_data()
                    pt = PrettyTable(['日期','金额','类型'])
                    list1 = user_dict[username]['bill']
                    for k,v in list1.items():   #列出用户账单
                        pt.add_row([k,v[0],v[1]])
                    print pt
                elif user_input == '1':   #列出用户信息
                    user_dict = read_user_data()
                    pt = PrettyTable(['名称','余额','状态','还款金额'])
                    pt.add_row([username,
                                user_dict[username]['money'],
                                user_dict[username]['status'],
                                user_dict[username]['overdraft'],
                                ])
                    print pt    

                elif user_input == '2':#转账
                    target_user = raw_input('\033[33m请输入户名：\033[0m').strip()
                    if target_user in user_dict:
                        number =  raw_input('\033[33m输入转入金额：\033[0m').strip()
                        if number.isdigit():
                            number = int(number)
                            play_money(username,target_user,number)
                             
                        else:
                            print'\033[31m请输入正确的金额。\033[0m' 
                elif user_input == '3': #现金还款
                    money_num = raw_input('\033[33m请输入还款金额：\033[0m').strip()
                    if money_num.isdigit():
                        money_num = int(money_num)
                        cash_repeayment(username,money_num)
                elif user_input == '4': #取现
                    money_num = raw_input('\033[33m请输入取现金额：\033[0m').strip()
                    if money_num.isdigit():
                        money_num = int(money_num)
                        cash_withdrawal(username,money_num)
                   
                elif user_input == '5': #用户退出
                    print '\033[31m 用户安全退出 \033[0m'
                    time.sleep(1)
                    print '\n'
                    man.man1() #转入主页
        #else:
        #    print '\033[31m该用户不存在，请重新输入\033[0m'
        
def shop_link_bank(total):
    username = raw_input('\033[33m请输入用户名：\033[0m')
    if user_login_bank(username):
        user_dict = read_user_data()
        date_now = str(datetime.datetime.now())
        if user_dict[username]['money'] >= total:
            user_dict[username]['money'] -= total
            user_dict[username]['overdraft'] += total
            user_dict[username]['bill'][date_now] = ['-'+str(total),'刷卡']  #生成账单
            write_data(user_dict)
            print '\033[33m恭喜你支付成功\033[0m'
            man.man1()
        else:
            print '\033[31m你的信用卡额度不足。\033[0m'
            time.sleep(1)
            print '\n'
            man.man1()
    else:
        print '\033[33m该用户不存在，请重新输入\033[0m'
        #shop_link_bank(total)
        #缺少判断
        
    #print 'new ---->', user_dict 

def play_money(source_user,target_user,number): #转账
    user_dict = read_user_data()
    date_now = str(datetime.datetime.now())
    if user_dict[source_user]['money'] >= number:
        #用户source_user付款生成账单
        user_dict[source_user]['money'] -= number
        user_dict[source_user]['overdraft'] += number
        user_dict[source_user]['bill'][date_now] = ['-'+str(number),'转账']  #生成账单
         
        if user_dict[target_user]['overdraft']:#
            if user_dict[target_user]['overdraft'] >= number: # 还款额度大于转账额度，从还款额度减
                user_dict[target_user]['overdraft'] -= number
                if user_dict[target_user]['overdraft'] == 0:
                    user_dict[target_user]['money'] = user_dict[target_user]['credit']
                print 'if-------->',user_dict
    
            elif user_dict[target_user]['overdraft'] < number:#还款额度小于于转账额度，
                                                               #从还款额度减完，把剩下的余额添加到总额度里面
                money_number =  number - user_dict[target_user]['overdraft']
                user_dict[target_user]['money'] += money_number
                user_dict[target_user]['overdraft'] = 0
                user_dict[target_user]['bill'][date_now] = ['+'+str(number),'转账']  #生成账单
        else:
            user_dict[target_user]['money'] += number
            user_dict[target_user]['bill'][date_now] = ['+'+str(number),'转账']  #生成账单
            #print user_dict
        write_data(user_dict)
        print '\033[31m转账成功\033[0m'
    elif user_dict[sourct_user]['total'] < number:
        print '\033[31m余额不足\033[0m'
        print '\033[31m转账失败\033[0m'
        #跳转回去

def cash_repeayment(user,cash): # 现金还款
    user_dict = read_user_data()
    date_now = str(datetime.datetime.now())
    user_dict[user]['bill'][date_now] = ['+'+str(cash),'现金还款']
    user_dict[user]['money'] += cash
    user_dict[user]['overdraft'] -= cash 
    if user_dict[user]['overdraft'] == 0:
        user_dict[user]['money'] = user_dict[user]['credit']
    write_data(user_dict)
    print '\033[31m还款成功\033[0m'

def cash_withdrawal(user,number):#取现
    user_dict = read_user_data()
    date_now = str(datetime.datetime.now())
    if user_dict[user]['money'] / 2 >= number:
        user_dict[user]['money'] -= number*2
        user_dict[user]['overdraft'] += number+number*0.05
        user_dict[user]['bill'][date_now] = ['-'+str(number),'取现'] 
        write_data(user_dict)
        print '\033[31m取现成功\033[0m'
    else:
        print '\033[31m取现失败，请检查您的额度\033[0m'


if __name__ == '__main__':
    #f = open('bank.pkl')
    #user_dict = pickle.load(f)
    #print user_dict
    #f.close()
    user_login_bank()







